package com.jt.service;

import com.jt.vo.ImageVO;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class fileServiceImpl implements FileService {
    private String locaDir = "D:/images2/";          //前端上传文件存储的位置
    private String urlPath = "http://image.jt.com/";
    private String deletePath;
    @Override
    public ImageVO upload(MultipartFile file) {
        String name = String.valueOf(file);
        System.out.println(name.toString());
        String filename = file.getOriginalFilename().toLowerCase();//获取图片真实名称并转换为小写
        System.out.println(filename);
        if(!filename.matches("^.+\\.(jpg|png|gif)$")){
            System.out.println("格式错误");
            return null;
        }
        try {
            BufferedImage image =  ImageIO.read(file.getInputStream());//获取图片长宽判断是否是图片
            Integer c = image.getHeight();
            Integer K  = image.getWidth();
            if(c.equals("")|| K.equals("")){
                System.out.println("不是图片");
                return null ;
            }
            String FilePath = locaDir + new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
            File file1 = new File(FilePath);
            if (!file1.exists()){
                System.out.println("路径不存在");
                file1.mkdirs();
            }
            String uuid = UUID.randomUUID().toString().replace("-","");
            int jname = filename.indexOf(".");
            String files = filename.substring(jname);
            String uuname = uuid + files ;
            String FIlePath = FilePath + uuname;
            deletePath = FIlePath ;
            file.transferTo(new File(FIlePath));//上传的要是哪个盘+哪个文件夹+全名称
            String virPath = FilePath + uuname ;
            String filenameVo = uuname ;
            String urlpath = urlPath + uuname  ;

            System.out.println(filename);

            return new ImageVO(virPath,urlpath,filename);

        }catch (Exception e ){
            e.printStackTrace();
        }
      return null;
    }
    @Override
    public void deleteFile(String virtualPath) {
        File file = new File(deletePath);
        if(file.exists()){
            file.delete();
        }
    }
}

